package com.xnx3.banmahuishou.userApplet.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.StringUtil;
import com.xnx3.banmahuishou.core.entity.Agency;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.banmahuishou.userApplet.util.UserLocationUtil;
import com.xnx3.banmahuishou.userApplet.vo.CartVO;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.pluginManage.controller.BasePluginController;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.shop.core.entity.Address;
import com.xnx3.wangmarket.shop.core.service.CartService;
import com.xnx3.wangmarket.shop.core.vo.AddressListVO;

/**
 * 用户收货地址相关
 * <p>一个用户会有多个收货地址，但一个用户默认的收货地址只有一个</p>
 * @author 管雷鸣
 */
@Controller("BanmahuishouUserAppletAddressController")
@RequestMapping("/userApplet/address/")
public class AddressController extends BasePluginController {
	@Resource
	private SqlService sqlService;
	@Resource
	private CartService cartService;
	/**
	 * 用户保存地址，包含新增、修改
	 * <p>如果当前用户保存的这个地址是他第一个地址，那自动将其设为默认地址</p>
	 * @param token 当前操作用户的登录标识 <required>
	 * 				<p>可通过 <a href="weixin.applet.login.loginByOpenid.json.html">/weixin/applet/login/loginByOpenid.json</a> 取得 </p>
	 * @param id 要修改的地址id， address.id ，如果这里不传入，或者传入0，则是新增地址
	 * @param username 收货人名字
	 * @param phone 收货人电话
	 * @param address 收货人地址
	 * @param sheng 所在的省,如： 山东省
	 * @param shi 所在的市，如 潍坊市
	 * @param qu 所在的区，如 寒亭区
	 * @param house 具体房间号，如 17号楼2单元202室
	 * @param longitude 经度，如 12.223344
	 * @param latitude 纬度，如 12.223344
	 * @param isDefault 当前地址是否为默认地址，若不传递此参数，默认是保存为非默认地址。 可传入值：
	 * 			<ul>
	 * 				<li>1:将当前地址设为默认地址</li>
	 * 				<li>0:将当前地址设为非默认地址(不传递此参数，默认就是这个)</li>
	 * 			</ul>
	 * @param sex 性别<ul><li>1:先生</li><li>2:女士</li></ul> 
	 * @return 成功后，会保存填写后的地址
	 * @author 管雷鸣
	 */
	@RequestMapping(value="save.json",method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO save(HttpServletRequest request,
			@RequestParam(value = "id", required = false, defaultValue = "0") int id,
			@RequestParam(value = "username", required = false, defaultValue = "") String username,
			@RequestParam(value = "phone", required = false, defaultValue = "") String phone,
			@RequestParam(value = "address", required = false, defaultValue = "") String address,
			@RequestParam(value = "sheng", required = false, defaultValue = "") String sheng,
			@RequestParam(value = "shi", required = false, defaultValue = "") String shi,
			@RequestParam(value = "qu", required = false, defaultValue = "") String qu,
			@RequestParam(value = "house", required = false, defaultValue = "") String house,
			@RequestParam(value = "longitude", required = false, defaultValue = "0") Double longitude,
			@RequestParam(value = "latitude", required = false, defaultValue = "0") Double latitude,
			@RequestParam(value = "isDefault", required = false, defaultValue = "") String isDefault,
			@RequestParam(value = "sex", required = false, defaultValue = "1") Short sex
			){
		int userid = getUserId();
		Address add = null;
		if(id > 0){
			//修改
			add = sqlService.findById(Address.class, id);
			if(add == null){
				return error("修改的地址不存在");
			}
			if(add.getUserid() - userid != 0){
				return error("地址不属于你，无法修改");
			}
		}else{
			//新增
			add = new Address();
			add.setUserid(userid);
		}
		add.setAddress(StringUtil.filterXss(address.replaceAll("\\(", "（").replaceAll("\\)", "）")));
		add.setLatitude(latitude);
		add.setLongitude(longitude);
		add.setPhone(StringUtil.filterXss(phone));
		add.setUsername(StringUtil.filterXss(username));
		add.setSheng(StringUtil.filterXss(sheng));
		add.setShi(StringUtil.filterXss(shi));
		add.setQu(StringUtil.filterXss(qu));
		add.setHouse(StringUtil.filterXss(house));
		add.setSex(sex);
		//判断isDefault是否传入值
		isDefault = isDefault.trim();
		if(isDefault.length() > 0) {
			//默认地址有变动
			if(isDefault.equals("1")){
				//将该地址设为默认地址

				//再将传入的地址设为默认
				add.setDefaultUse((short) 1);
			}else if(isDefault.equals("0")){
				// 将该地址设为非默认地址
				add.setDefaultUse((short) 0);
			}
		}

		//查询一下当前用户是否有过其他地址，如果这是用户第一个地址，那么将其设为默认地址
		if(sqlService.count("shop_address", "WHERE userid = " + userid) < 1) {
			//没有过地址，那就将当前地址设为默认地址
			add.setDefaultUse((short) 1);
		}
		sqlService.save(add);

		//如果是一起设置了默认地址，那么需要把之前的默认地址全部取消掉
		if(isDefault.equals("1")){
			sqlService.executeSql("UPDATE shop_address SET default_use = 0 WHERE userid = " + userid + " AND default_use = 1 AND id <> " + add.getId());
		}

		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		// 新增地址,无论是否是默认地址都更新一下购物车
		if (id <= 0) {
			Address ad = new Address();
			BeanUtils.copyProperties(add, ad);	//bean复制
			vo.setAddress(ad);
			//更新缓存
			cartService.setCurrentUserCacheCartVO(vo);
		}else {
			if (isDefault.equals("1")) {
				Address ad = new Address();
				BeanUtils.copyProperties(add, ad);	//bean复制
				vo.setAddress(ad);
				//更新缓存
				cartService.setCurrentUserCacheCartVO(vo);
			}
		}

		//日志记录
		ActionLogUtil.insertUpdateDatabase(request, id,"保存收货地址", address.toString());

		return success();
	}


	/**
	 * 用户删除地址
	 * @param id 要删除的地址id， address.id
	 * @author zxy
	 * @return 操作结果
	 */
	@RequestMapping(value="delete.json",method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO deleteAddress(HttpServletRequest request,
			@RequestParam(value = "id", required = true, defaultValue = "0") int id) {
		int userid = getUserId();
		Address address = sqlService.findById(Address.class, id);
		if(address == null){
			return error("删除的地址不存在");
		}
		if(address.getUserid() - userid != 0){
			return error("地址不属于你，无法删除");
		}
		sqlService.delete(address);
		if (address.getDefaultUse() - 1 == 0) {
			//获取当前缓存
			CartVO vo = cartService.getCurrentUserCacheCartVO();
			// 如果删除的地址是默认地址的话 就把购物车中的比较一下看看是的话 删除缓存
			if (vo.getAddress() != null && vo.getAddress().getId() - address.getId() == 0) {
				vo.setAddress(null);
				//更新缓存
				cartService.setCurrentUserCacheCartVO(vo);
			}
		}
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request, userid,"删除收货地址", address.toString());
		return success();
	}




	/**
	 * 获取用户地址列表，包含默认地址跟其他非默认地址列表
	 * @param token 当前操作用户的登录标识 <required>
	 * 				<p>可通过 <a href="shop.api.login.login.json.html">/shop/api/login/login.json</a> 取得 </p>
	 * @author 管雷鸣
	 * @return 地址列表
	 */
	@RequestMapping(value="list.json",method = {RequestMethod.POST})
	@ResponseBody
	public AddressListVO list(HttpServletRequest request) {
		AddressListVO vo = new AddressListVO();
		User user = getUser();

		//查询用户地址信息
		List<Address> addressList = sqlService.findBySqlQuery("SELECT * FROM shop_address WHERE userid = " + user.getId() + " ORDER BY default_use DESC", Address.class);

		/*
		 * 找出
		 * 1. 默认地址
		 * 2. 所有的地址的列表
		 */
		for (int i = 0; i < addressList.size(); i++) {
			Address address = addressList.get(i);
			if(address.getDefaultUse() != null && address.getDefaultUse() - 1 == 0){
				//是默认的
				vo.setDefaultAddress(address);
			}
		}
		vo.setAddressList(addressList);

		//日志记录
		ActionLogUtil.insert(request, "获取用户地址列表");
		return vo;
	}




	/**
	 * 判断当前区域是否开放
	 * @param token 当前操作用户的登录标识 <required>
	 * 				<p>可通过 <a href="weixin.applet.login.loginByOpenid.json.html">/weixin/applet/login/loginByOpenid.json</a> 取得 </p>
	 * @param sheng 所在的省,如 山东省
	 * @param shi 所在的市，如 潍坊市
	 * @param qu 所在的区，如 寒亭区
	 * @return 成功后，说明该地区已开放
	 * @author qyw
	 */
	@RequestMapping(value="isUsed.json",method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO isUsed(HttpServletRequest request,
			@RequestParam(value = "sheng", required = false, defaultValue = "") String sheng,
			@RequestParam(value = "shi", required = false, defaultValue = "") String shi,
			@RequestParam(value = "qu", required = false, defaultValue = "") String qu){

		int userId = getUserId();
		if (userId == 0) {
			return notLogin();
		}
		List<Agency> list = sqlService.findAll(Agency.class);
		List<String> shengList = new ArrayList<String>();
		List<String> shiList = new ArrayList<String>();
		List<String> quList = new ArrayList<String>();
		for (Agency agency : list) {
			String addminArea = agency.getAddminArea();
			if (addminArea != null && StringUtils.hasLength(addminArea)) {
				String[] split = addminArea.split(",");
				// 存省
				if (split.length == 1) {
					shengList.add(split[0]);
				}
				// 存省、市
				if (split.length == 2) {
					shengList.add(split[0]);
					shiList.add(split[1]);
				}
				// 存省、市、区
				if (split.length == 3) {
					shengList.add(split[0]);
					shiList.add(split[1]);
					quList.add(split[2]);
				}
			}
		}
		// 如果是直辖市 就判断两级
		if (sheng.length() == 3 && ObjectUtils.equals(sheng.substring(2), "市") ) {
			if (!shengList.contains(sheng)) {
				return error("抱歉,当前区域未开放");
			}
			if (!quList.contains(qu)) {
				return error("抱歉,当前区域未开放");
			}
		}else {
			if (!shengList.contains(sheng)) {
				return error("抱歉,当前区域未开放");
			}
			if (!shiList.contains(shi)) {
				return error("抱歉,当前区域未开放");
			}
			if (!quList.contains(qu)) {
				return error("抱歉,当前区域未开放");
			}
		}

		return success();
	}



	/**
	 * 保存微信登录用户的昵称和头像
	 * @param token 当前操作用户的登录标识 <required>
	 * 				<p>可通过 <a href="weixin.applet.login.loginByOpenid.json.html">/weixin/applet/login/loginByOpenid.json</a> 取得 </p>
	 * @param head		头像
	 * @param nickname	昵称
	 * @return 成功后，获取微信登录用户的昵称和头像保存到user表
	 * @author qyw
	 */
	@RequestMapping(value="updateUserInfo.json", method= {RequestMethod.POST})
	@ResponseBody
	public BaseVO updateUserInfo(HttpServletRequest request, @RequestParam(value="head",defaultValue = "") String head,@RequestParam(value="nickname",defaultValue = "") String nickname){

		User user = sqlService.findById(User.class, getUserId());
		if(user == null){
			return notLogin();
		}
		if (!StringUtils.hasLength(head)) {
			return error("请传入头像");
		}
		if (!StringUtils.hasLength(head)) {
			return error("请传入昵称");
		}
		user.setHead(head);
		user.setNickname(nickname);
		sqlService.save(user);
		//日志插入
		ActionLogUtil.insertUpdateDatabase(request, user.getId(), "保存微信登录用户的昵称和头像", "更改后的用户信息: " + user.toString()); //记录日志
		return success();
	}


	/**
	 * 判断当前区域是否开放(v2)
	 * @param token 当前操作用户的登录标识 <required>
	 * 				<p>可通过 <a href="weixin.applet.login.loginByOpenid.json.html">/weixin/applet/login/loginByOpenid.json</a> 取得 </p>
	 * @param sheng 	所在的省,如： 山东省
	 * @param shi 		所在的市，如 潍坊市
	 * @param qu 		所在的区，如 寒亭区
	 * @param lat		纬度
	 * @param lon		经度
	 * @return 成功后，说明该地区已开放
	 * @author qyw
	 */
	@RequestMapping(value="isUsedv2.json",method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO isUsedv2(HttpServletRequest request,
			@RequestParam(value = "sheng", required = false, defaultValue = "") String sheng,
			@RequestParam(value = "shi", required = false, defaultValue = "") String shi,
			@RequestParam(value = "qu", required = false, defaultValue = "") String qu,
			@RequestParam(value = "lat", required = false,defaultValue = "0") double lat,
			@RequestParam(value = "lon", required = false,defaultValue = "0") double lon){

		int userId = getUserId();
		User user = sqlService.findById(User.class, userId);
		if (user == null) {
			return notLogin();
		}
		// 判断是哪个代理商
		String string = "SELECT * FROM laji_agency WHERE state = 1 AND userid > 1";
		List<Agency> list = sqlService.findBySqlQuery(string, Agency.class);
		int dlsUserid = UserLocationUtil.getDlsUserid(sheng, shi, qu, list);
		if (dlsUserid <= 0) {
			return error("抱歉,当前区域未开放");
		}
		// 判断是哪个网格
		string = "SELECT * FROM laji_wangge WHERE state = 1 AND dailishang_userid = " + dlsUserid;
		List<Wangge> wgList = sqlService.findBySqlQuery(string, Wangge.class);
		// 是否在网格 0:不在 ,1:在
		int isIn = 0;
		for (Wangge wangge : wgList) {
			Boolean b = UserLocationUtil.isWgLocation(lon, lat, wangge.getServiceArea());
			if (b) {
				isIn = 1;
			}
		}
		if (isIn == 0) {
			return error("抱歉,当前区域未开放");
		}
		return success();
	}



}
